<?php

namespace org\copperforest\oak\resources;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ResourceList
 *
 * @author agama
 */
class Collection extends ResponseNode
{
    protected $childs = array( );
    protected $childsQuery = '';
    protected $childsFactory;
    protected $order;

    
    public function setChildsFactory( $factory ){
        $this->childsFactory = $factory;
    }
            
    //The subclasses must to overwrite the method to eval $_GET[ 'q' ] to establish $this->qEvaluated
    public function evalueAndFetch()
    {
        if( isset( $this->GET[ 'p' ] ) ){
            $this->GET[ 'p' ] = (float) sprintf('%u', $this->GET[ 'p' ] );
        }
        if ( empty( $this->GET[ 'p' ] ) ) {
            $this->GET[ 'p' ] = 1;
        }
        
        if( isset( $this->GET[ 'n' ] ) ){
            $this->GET[ 'n' ] = (float) sprintf('%u', $this->GET[ 'n' ] );
        }
        if ( empty( $this->GET[ 'n' ] ) ) {
            $this->GET[ 'n' ] = 50;
        }
        
        if( isset( $this->GET[ 'o' ] ) ){
            $this->GET[ 'o' ] = strtoupper( $this->GET[ 'o' ] );
        }
        
        $l = strlen( $this->GET[ 'o' ] );
        
        for ( $i=0; $i < $l ; $i++ ) {
            if( !in_array( $this->GET[ 'o' ][ $i ], array( 'A', 'D', 'U' ) ) ){
                $this->GET['o'][ $i ] = 'U';
            }
        }
        
        if( isset( $this->GET[ 't' ] ) ){
            $this->GET[ 't' ] = (float) sprintf('%u', $this->GET[ 't' ] );
        }
        
       //Subclass must parse 'g' and 'q'
       //$context->get[ 'g' ] 
       //$context->get[ 'q' ]
       //Subclass must to establish qProcessed, parsing $context->get[ 'q' ], $context->backtrace, $context->pathParams
   
        $order=array();
        foreach( $this->order as $i => $o ){
            $order[ $o ] = $this->GET[ 'o' ][ $i ];
        }
        
        if( !isset( $this->GET[ 'c' ] ) ){
            $this->GET[ 'c' ] = null;
        }
        
        //El contexto de los hijos????
        $this->childs =  $this->childsFactory->fetchArray(
                        $this->childsQuery, //Para procesar ['q'] ya debería saber el tipo de DataSource
                        $this->GET[ 'n' ], 
                        $this->GET[ 'p' ], 
                        $order,
                        isset( $this->GET[ 'g' ] ) ? $this->GET[ 'g' ] : null, $this->GET[ 'c' ] );
        
        //El ultimo ancestor debería tener sus ids, el get quizá nada y el pathparams???
        //O lo hereda todo del padre?...no...o si?s

        foreach( $this->childs as $c ){
            $c->setConfiguration( $this->configuration->fetch( '/'.implode('/', $c->id ) ) );
        }
    }
    
}